package samples;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import util.Printer;
import util.RxJavaHelper;

class QueryCacheWithFirstOrError {

//    private static String disk    = "缓存中的数据";
//    private static String netWork = "网络中的数据";
//    private static String memory  = "内存中的数据";

    private static String disk    ;
    private static String netWork ;
    private static String memory  ;

    public static void main(String[] args) {
        queryData();
    }

    static void queryData() {
        Observable<String> fromMemory = Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> e) throws Exception {
                if (memory == null) {
                    e.onComplete();
                } else {
                    e.onNext(memory);
                    Printer.print("获取到memory数据");
                }
            }
        });
        Observable<String> fromDisk = Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> e) throws Exception {
                if (disk == null) {
                    e.onComplete();
                } else {
                    e.onNext(disk);
                    Printer.print("获取到disk数据");
                }
            }
        });

        Observable<String> fromNetWork = Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> e) throws Exception {
                if (netWork == null) {
                    e.onComplete();
                } else {
                    e.onNext(netWork);
                    Printer.print("获取到network数据");
                }
            }
        });
        //对三个被观察者串行合并成一个队列
        Observable.concat(fromMemory, fromDisk, fromNetWork)
                //取出第一个发送数据的，如果取不到则发出onError
                .firstOrError()
                .subscribe(RxJavaHelper.getSingleConsumer());
    }

}
